package org.mzx.shortLink.work.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;

import org.mzx.shortLink.starter.convention.Result.Result;
import org.mzx.shortLink.starter.web.Results;

import org.mzx.shortLink.work.domain.entity.TLink;
import org.mzx.shortLink.work.dto.Request.TLinkCountDtoReq;
import org.mzx.shortLink.work.dto.Request.TLinkCreateDtoReq;
import org.mzx.shortLink.work.dto.Request.TLinkUpdateDtoReq;
import org.mzx.shortLink.work.dto.Response.TLinkCreateDtoResp;
import org.mzx.shortLink.work.dto.Response.TLinkPageDtoResp;
import org.mzx.shortLink.work.service.TLinkService;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequiredArgsConstructor
public class TLnkController {

    private final TLinkService service;

    /**
     * 创建短链接
     * @param requestParam
     * @return
     */
    @PostMapping("/api/short-link/v1/create")
    public Result<TLinkCreateDtoResp> create(@RequestBody TLinkCreateDtoReq requestParam) {

        return Results.success(service.create(requestParam));
    }

    /**
     * 分页查询短链接
     * @param gid
     * @param current
     * @param size
     * @return
     */
    @GetMapping("/api/short-link/v1/page")
    public Result<IPage<TLinkPageDtoResp>> getByPage(@RequestParam("gid") String gid, @RequestParam("current") Long current, @RequestParam("size") Long size, @RequestParam(value = "orderTag",required = false) String orderTag) {
        Page<TLink> page = new Page<>(current,size);
        return Results.success(service.getByPage(gid,page,orderTag));
    }

    /**
     * 查询短链接分组下的总短连接数目
     * @param requestParam
     * @return
     */
    @PostMapping("/api/short-link/v1/count")
    public Result<Map<String,Map<String, Object>>> count(@RequestBody List<TLinkCountDtoReq> requestParam) {
        Map<String, Map<String, Object>> count = service.Count(requestParam);
        return Results.success(count);
    }

    /**
     * 修改短链接
     * @param requestParam
     * @return
     */
    @PostMapping("/api/short-link/v1/update")
    public Result<Void> update(@RequestBody TLinkUpdateDtoReq requestParam) {
        return Results.success(service.Update(requestParam));
    }


    /**
     * 短链接重定向
     * @param shortUrl
     * @param httpRequest
     * @param httpResponse
     */
    @GetMapping("/{short-uri}")
    public void reDirect(@PathVariable(value = "short-uri") String shortUrl, HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
        service.reDirect(shortUrl,httpRequest,httpResponse);
    }
}
